package com.cskaoyan.service;

import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.data.*;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.domain.*;
import com.cskaoyan.mapper.*;
import com.github.pagehelper.PageHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Transactional
@Service
public class WxOrderServiceImpl implements WxOrderService {

    @Autowired
    MarketCommentMapper marketCommentMapper;

    @Autowired
    MarketOrderGoodsMapper marketOrderGoodsMapper;
    @Autowired
    MarketOrderMapper marketOrderMapper;
    @Autowired
    MarketCartMapper marketCartMapper;
    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;
    @Autowired
    CartService marketCartService;
    @Autowired
    MarketAddressMapper marketAddressMapper;
    @Autowired
    MarketCouponMapper marketCouponMapper;


    @Override
    public WxOrderDetail detail(Integer orderId) {
        //响应order_goods
        List<MarketOrderGoods> marketOrderGoods = insertMarketGoods(orderId);


        //响应order_info
        MarketOrder marketOrder = getMarketOrder(orderId);

        WxOrderDetail wxOrderList = new WxOrderDetail();
//        wxOrderList.setExpressInfo();
        wxOrderList.setMarketOrderGoods(marketOrderGoods);
        wxOrderList.setMarketOrders(marketOrder);


        return wxOrderList;
    }

    private MarketOrder getMarketOrder(Integer orderId) {
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        Short orderStatus = marketOrder.getOrderStatus();
        WxOrderHandleOption handleOption = new WxOrderHandleOption();
        if (orderStatus == 401 || orderStatus == 402) {
            handleOption.setAftersale(true);
            handleOption.setCancel(false);
            handleOption.setComment(true);
            handleOption.setConfirm(false);
            handleOption.setDelete(true);
            handleOption.setPay(false);
            handleOption.setRebuy(true);
            handleOption.setRefund(false);
        }  else if (orderStatus == 201 || orderStatus == 202) {
            handleOption.setAftersale(false);
            handleOption.setCancel(false);
            handleOption.setComment(false);
            handleOption.setConfirm(false);
            handleOption.setDelete(false);
            handleOption.setPay(false);
            handleOption.setRebuy(false);
            handleOption.setRefund(true);
        } else if (orderStatus == 301 ) {
            handleOption.setAftersale(false);
            handleOption.setCancel(false);
            handleOption.setComment(true);
            handleOption.setConfirm(true);
            handleOption.setDelete(false);
            handleOption.setPay(false);
            handleOption.setRebuy(false);
            handleOption.setRefund(false);
        }else if (orderStatus == 101 ) {
            handleOption.setAftersale(false);
            handleOption.setCancel(true);
            handleOption.setComment(false);
            handleOption.setConfirm(false);
            handleOption.setDelete(false);
            handleOption.setPay(false);
            handleOption.setRebuy(false);
            handleOption.setRefund(false);
        } else {
            handleOption.setAftersale(true);
            handleOption.setCancel(true);
            handleOption.setComment(true);
            handleOption.setConfirm(true);
            handleOption.setDelete(true);
            handleOption.setPay(false);
            handleOption.setRebuy(false);
            handleOption.setRefund(true);
        }
        marketOrder.setHandleOption(handleOption);
        return marketOrder;
    }


    private List<MarketOrderGoods> insertMarketGoods(Integer orderId) {
        MarketOrderGoodsExample example = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = example.createCriteria();

        if (orderId != null) {
            criteria.andOrderIdEqualTo(orderId);
        }
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(example);

        return marketOrderGoods;
    }

    @Override
    public void comment(WxOrderComment wxOrderComment) {
        MarketComment marketComment = new MarketComment();
        getMarketComment(wxOrderComment, marketComment);

        marketCommentMapper.insert(marketComment);
    }

    @Override
    public CommonData list(Integer showType, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        //  全部    为0
        //  101 代付款 1
        //  202 代发货 2
        // 301 待收货  3
        // 401 用户收货 4


        MarketOrderExample example = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = example.createCriteria();
        //声明一个list装order order_good 和 handleOption
        List<WxOrderList> list = new ArrayList<>();
        //找到订单状态对应的list
        if (showType == 0) {
//            criteria.andAftersaleStatusEqualTo(null);
        } else if (showType == 1) {
            criteria.andOrderStatusEqualTo((short) 101);
        } else if (showType == 2) {
            criteria.andOrderStatusEqualTo(((short) 202));
        } else if (showType == 3) {
            criteria.andOrderStatusEqualTo(((short) 301));
        } else {
            criteria.andOrderStatusEqualTo(((short) 401));
        }

        List list1 = getList(example, list);

        return CommonData.data(list1);
    }

    @Override
    public BaseRespVo cancel(Integer orderId) {
        //通过orderId将订单状态从为101改为102
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        if (marketOrder.getOrderStatus() == 101) {

            marketOrder.setOrderStatus(((short) 102));
            marketOrderMapper.updateByPrimaryKey(marketOrder);
            return BaseRespVo.ok();
        } else {
            return BaseRespVo.fail("此订单不能取消");
        }


    }

    @Override
    public BaseRespVo refund(Integer orderId) {
        //将订单状态从201更改为202
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        if (marketOrder.getOrderStatus() == 201||marketOrder.getOrderStatus()==202) {

            marketOrder.setOrderStatus(((short) 203));
            marketOrder.setDeleted(true);
            marketOrderMapper.updateByPrimaryKey(marketOrder);
        }
        return BaseRespVo.ok();
    }

    @Override
    public BaseRespVo delete(Integer orderId) {
        //订单状态为401，将其delete属性改为1
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        if (marketOrder.getOrderStatus() == 401) {

            marketOrder.setDeleted(true);
            marketOrderMapper.updateByPrimaryKey(marketOrder);
            return BaseRespVo.ok();
        } else {
            return BaseRespVo.fail("此订单不能删除");
        }
    }

    @Override
    public BaseRespVo confirm(Integer orderId) {
        //订单状态为401，将其delete属性改为1
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        if (marketOrder.getOrderStatus() == 301) {

            marketOrder.setOrderStatus(((short) 401));
            marketOrderMapper.updateByPrimaryKey(marketOrder);
            return BaseRespVo.ok();
        } else {
            return BaseRespVo.fail("此订单不能证实");
        }
    }

    @Override
    public OrderGoods goods(Integer orderId, Integer goodsId) {
        //将响应报文装入OrderGoods中
        OrderGoods orderGoods = new OrderGoods();

        //查询goods_order表得到对应数据
        getOrederGoods(orderId, goodsId, orderGoods);

        return orderGoods;
    }

    @Override
    public BaseRespVo submit(WxOrderSubmit wxOrderSubmit) {
        MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(wxOrderSubmit.getAddressId());
        //插入market_order
        MarketOrder marketOrder = new MarketOrder();
        //user_id写死需要改
        marketOrder.setUserId(marketAddress.getUserId());
        marketOrder.setOrderStatus(((short) 101));
        marketOrder.setAftersaleStatus(((short) 0));
        //consignee
        marketOrder.setConsignee(marketAddress.getName());
        //mobile
        marketOrder.setMobile(marketAddress.getTel());
        //address
        marketOrder.setAddress(marketAddress.getAddressDetail());
        //message
        marketOrder.setMessage(wxOrderSubmit.getMessage());
        //good_price
        MarketCart marketCart = marketCartMapper.selectByPrimaryKey(wxOrderSubmit.getCartId());
        BigDecimal goodsPrice = marketCart.getPrice();
        marketOrder.setGoodsPrice(goodsPrice);
        //freight_price'配送费用
        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(wxOrderSubmit.getCouponId());


        BigDecimal freightPrice = new BigDecimal("10");
        marketOrder.setFreightPrice(freightPrice);

        //coupon_price优惠券减免
        BigDecimal couponDiscount = marketCoupon.getDiscount();
        marketOrder.setCouponPrice(couponDiscount);
        //order_price

        BigDecimal orderPrice = goodsPrice.subtract(couponDiscount).add(freightPrice);
        marketOrder.setOrderPrice(orderPrice);

        //integral_price用户积分减免
        BigDecimal integralPrice = new BigDecimal("20");
        marketOrder.setIntegralPrice(orderPrice.subtract(integralPrice));

        //groupon_price

        //   actual_price
        marketOrder.setActualPrice(orderPrice.subtract(integralPrice));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String orderSn = simpleDateFormat.format(new Date());
        marketOrder.setOrderSn(orderSn);
        marketOrder.setConsignee("桐人");
        //goods_price
        //...
        marketOrderMapper.insertSelective(marketOrder);


        //添加market_goods的数量
        insertMarketGoods(wxOrderSubmit, marketOrder);

        //删除购物车中的记录
//        MarketCart marketCart = marketCartMapper.selectByPrimaryKey(wxOrderSubmit.getCartId());
        marketCart.setDeleted(true);
        marketCartMapper.updateByPrimaryKey(marketCart);
        Short number = marketCart.getNumber();
        //减少库存
        Integer goodsId = marketCart.getGoodsId();
        String[] specifications = marketCart.getSpecifications();

        MarketGoodsProductExample example = new MarketGoodsProductExample();
        MarketGoodsProductExample.Criteria criteria = example.createCriteria();
        if (goodsId != null) {
            criteria.andGoodsIdEqualTo(goodsId);
        }
        if (specifications != null) {
            criteria.andSpecificationsEqualTo(specifications);
        }
        List<MarketGoodsProduct> marketGoodsProducts = marketGoodsProductMapper.selectByExample(example);
        for (MarketGoodsProduct marketGoodsProduct : marketGoodsProducts) {
            if (number > marketGoodsProduct.getNumber()){
                return BaseRespVo.fail("没货了，回家吧");
            }else {
                marketGoodsProduct.setNumber(marketGoodsProduct.getNumber() - number);
                marketGoodsProductMapper.updateByPrimaryKey(marketGoodsProduct);
            }
        }

        //成功
        Subject subject = SecurityUtils.getSubject();
        Integer userId=0;
        if (subject.isAuthenticated()) {
            MarketUser principal = (MarketUser) subject.getPrincipal();
            userId = principal.getId();
        }
        BaseRespVo index = marketCartService.selectCartIndexByUserId(userId);
        return BaseRespVo.ok(index.getData());
    }

    private void insertMarketGoods(WxOrderSubmit wxOrderSubmit, MarketOrder marketOrder) {
        MarketOrderGoods marketOrderGoods = new MarketOrderGoods();
        //获得订单数量
        MarketCart marketCart = marketCartMapper.selectByPrimaryKey(wxOrderSubmit.getCartId());
        Short cartNumber = marketCart.getNumber();
        marketOrderGoods.setNumber(cartNumber);
        marketOrderGoods.setOrderId(marketOrder.getId());
        marketOrderGoods.setGoodsId(marketCart.getGoodsId());
        marketOrderGoods.setGoodsName(marketCart.getGoodsName());
        marketOrderGoods.setGoodsSn(marketCart.getGoodsSn());
        marketOrderGoods.setProductId(marketCart.getProductId());
        marketOrderGoods.setPrice(marketCart.getPrice());
        marketOrderGoods.setSpecifications(marketCart.getSpecifications());
        marketOrderGoods.setPicUrl(marketCart.getPicUrl());
        marketOrderGoods.setComment(0);
        marketOrderGoods.setAddTime(LocalDateTime.now());
        marketOrderGoods.setUpdateTime(LocalDateTime.now());
        marketOrderGoods.setDeleted(false);
        marketOrderGoodsMapper.insert(marketOrderGoods);
    }

    private void getOrederGoods(Integer orderId, Integer goodsId, OrderGoods orderGoods) {
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);

        //找到对应的market_order_goods
        MarketOrderGoodsExample example = new MarketOrderGoodsExample();

        MarketOrderGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andGoodsIdEqualTo(goodsId);
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(example);
        MarketOrderGoods realMarketOrderGoods = null;
        for (MarketOrderGoods marketOrderGood : marketOrderGoods) {
            if (marketOrderGood.getOrderId() == orderId) {
                realMarketOrderGoods = marketOrderGood;
            }
        }
        orderGoods.setAddTime(LocalDateTime.now());
        orderGoods.setComment(marketOrder.getComments());
        orderGoods.setDeleted(marketOrder.getDeleted());
        orderGoods.setGoodsId(goodsId);
        orderGoods.setGoodsName(realMarketOrderGoods.getGoodsName());
        orderGoods.setGoodsSn(realMarketOrderGoods.getGoodsSn());
        orderGoods.setId(realMarketOrderGoods.getId());
        orderGoods.setNumber(realMarketOrderGoods.getNumber());
        orderGoods.setOrderId(orderId);
        orderGoods.setPicUrl(realMarketOrderGoods.getPicUrl());
        orderGoods.setPrice(realMarketOrderGoods.getPrice());
        orderGoods.setProductId(realMarketOrderGoods.getProductId());
        orderGoods.setSpecifications(realMarketOrderGoods.getSpecifications());
        orderGoods.setUpdateTime(LocalDateTime.now());
    }

    private List getList(MarketOrderExample example, List<WxOrderList> list) {
        List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(example);

        for (MarketOrder marketOrder : marketOrders) {
            //给wxOrderList赋值 他是响应报文的部分
            WxOrderList wxOrderList = new WxOrderList();

            wxOrderList.setWxOrderHandleOption(new WxOrderHandleOption(false, false, false, false, false, false, false, false));
            wxOrderList.setActualPrice(marketOrder.getActualPrice());
            wxOrderList.setAftersaleStatus(marketOrder.getAftersaleStatus());

            //查询order_goods
            List<MarketOrderGoods> marketOrderGoods = getMarketOrderGoods(marketOrder);

            wxOrderList.setGoodsList(marketOrderGoods);
            wxOrderList.setId(marketOrder.getId());
            wxOrderList.setIsGroupin(false);
            wxOrderList.setOrderSn(marketOrder.getOrderSn());
            String text = getTextByAftersaleStatus(marketOrder.getOrderStatus());
            wxOrderList.setOrderStatusText(text);
            list.add(wxOrderList);

        }
        //list响应报文的list部分
        return list;
    }

    private String getTextByAftersaleStatus(Short aftersaleStatus) {
        String text = null;
        if (aftersaleStatus == 101) {
            text = "未付款";
        }
        if (aftersaleStatus == 102) {
            text = "用户取消";
        }
        if (aftersaleStatus == 103) {
            text = "系统取消";
        }
        if (aftersaleStatus == 201) {
            text = "已付款";
        }
        if (aftersaleStatus == 202) {
            text = "已付款";
        }
        if (aftersaleStatus == 203) {
            text = "已退款";
        }
        if (aftersaleStatus == 301) {
            text = "已发货";
        }
        if (aftersaleStatus == 401) {
            text = "用户收货";
        }
        if (aftersaleStatus == 402) {
            text = "系统收货";
        }
        return text;
    }

    private List<MarketOrderGoods> getMarketOrderGoods(MarketOrder marketOrder) {
        MarketOrderGoodsExample exampl = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria1 = exampl.createCriteria();
        criteria1.andOrderIdEqualTo(marketOrder.getId());
        return marketOrderGoodsMapper.selectByExample(exampl);
    }

    private void getMarketComment(WxOrderComment wxOrderComment, MarketComment marketComment) {
        marketComment.setValueId(wxOrderComment.getOrderGoodsId());
        marketComment.setType(((byte) 0));
        marketComment.setContent(wxOrderComment.getContent());
        //user_id未改动
        marketComment.setUserId(2);

        if (wxOrderComment.getPicUrls() != null) {
            marketComment.setHasPicture(true);
        } else {
            marketComment.setHasPicture(false);
        }

        marketComment.setPicUrls(wxOrderComment.getPicUrls());

        int star = wxOrderComment.getStar();
        marketComment.setStar((short) star);

        marketComment.setAddTime(LocalDateTime.now());
        marketComment.setUpdateTime(LocalDateTime.now());
        marketComment.setDeleted(false);
    }
    @Override
    public int getCountByStatus(short status) {
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        marketOrderExample.createCriteria().andOrderStatusEqualTo(status);
        Integer l = (int) marketOrderMapper.countByExample(marketOrderExample);
        return l;
    }
}
